<?php


namespace app\admin\controller;


use app\common\model\AdminModel;
use app\common\model\AnchorBannedModel;
use app\common\model\LiveModel;
use app\common\model\UserModel;
use app\common\model\ConfigTagModel;
use app\common\model\AnchorFansModel;
use app\common\model\AdminRoleModel;
use think\db\Query;
use think\facade\Request;

class AdminController extends BaseController
{

    public function index()
    {
        $this->assign('currAdmin', $this->userinfo);
        return $this->fetch();
    }

    public function add()
    {
        $role = AdminRoleModel::where(['status' => 1])->select();
        $this->assign('role', $role);
        return $this->fetch();
    }

    public function edit()
    {
        $role = AdminRoleModel::where(['status' => 1])->select();
        $this->assign('role', $role);
        $admin = AdminModel::where(['id' => Request::param('id')])->find();
        $this->assign('admin', $admin);
        return $this->fetch();
    }

    public function getList()
    {
        $admin = AdminModel::with('role')->field('password,token', true)->select();
        return self::bulidSuccess($admin);
    }

    public function add_post()
    {
        $params             = Request::param();
        $admin              = new AdminModel($params);
        $admin->password    = openssl_encrypt($admin->account . "123456", "DES-ECB", $this->OPENSSL_KEY);
        $admin->create_time = nowFormat();

        // 查询名称和登录名是否存在
        $check = AdminModel::where('name', $admin->name)->find();
        if ($check) {
            return self::bulidFail('名称已存在，请更换');
        }

        $check = AdminModel::where('account', $admin->account)->find();
        if ($check) {
            return self::bulidFail('登录名已存在，请更换');
        }

        if ($admin->save()) {
            // 记录日志
            $log_content = "添加角色用户，ID：{$admin->id},名称：{$admin->name}";
            parent::addAdminLog($log_content);
            return self::bulidSuccess([], '添加成功，默认密码123456');
        }
        return self::bulidFail();
    }

    public function edit_post()
    {
        $admin = AdminModel::where(['id' => Request::param('id')])->find();
        if (!$admin) {
            return self::bulidFail('用户状态异常');
        }
        $admin->status   = Request::param('status');
        $admin->name   = Request::param('name');
        $admin->roleid = Request::param('roleid');

        // 查询名称和登录名是否存在
        $c_where = [
            ['id', '<>', $admin->id],
            ['name', '=', $admin->name],
        ];
        $check = AdminModel::where($c_where)->find();
        if ($check) {
            return self::bulidFail('名称已存在，请更换');
        }

        $c_where = [
            ['id', '<>', $admin->id],
            ['name', '=', $admin->account],
        ];
        $check = AdminModel::where($c_where)->find();
        if ($check) {
            return self::bulidFail('登录名已存在，请更换');
        }

        if ($admin->save()) {
            // 记录日志
            $log_content = "编辑角色用户，ID：{$admin->id},名称：{$admin->name}";
            parent::addAdminLog($log_content);
            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function del_post()
    {
        $id    = Request::param('id');
        $admin = AdminModel::get($id);
        if (!$admin) {
            return self::bulidFail('角色用户不存在');
        }

        if (AdminModel::where(['id' => $id])->delete()) {
            // 记录日志
            $log_content = "删除角色用户，ID：{$admin->id},名称：{$admin->name}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function reset_password()
    {
        $id = Request::post("id", 0);
        if ($id <= 0) {
            return self::bulidFail("ID 不能为空");
        }

        $admin = AdminModel::where(['id' => $id])->find();
        if (!$admin) {
            return self::bulidFail("数据不存在或已删除");
        }

        if ($this->userinfo->role->id != 1) {
            return self::bulidFail("只有超管能进行重置密码，请联系超管");
        }

        $admin->password    = openssl_encrypt($admin->account . "venom123456", "DES-ECB", $this->OPENSSL_KEY);
        $admin->create_time = nowFormat();
        if ($admin->save()) {
            // 记录日志
            $log_content = "重置角色用户密码，ID：{$admin->id},名称：{$admin->name}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess([], '重置成功，默认密码为：账号+venom123456');
        }
        return self::bulidFail();
    }

    /**
     * 重置google身份验证
     * @return \think\response\Json
     */
    public function reset_google_secret()
    {
        $id = Request::post("id", 0);
        if ($id <= 0) {
            return self::bulidFail("ID 不能为空");
        }

        $admin = AdminModel::where(['id' => $id])->find();
        if (!$admin) {
            return self::bulidFail("数据不存在或已删除");
        }

        if ($this->userinfo->role->id != 1) {
            return self::bulidFail("只有超管能进行重置google身份验证，请联系超管");
        }

        $admin->google_secret = '';
        if ($admin->save()) {
            // 记录日志
            $log_content = "重置角色google身份验证秘钥，ID：{$admin->id},名称：{$admin->name}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess([], '重置成功');
        }
        return self::bulidFail();
    }

    public function sub_anchors()
    {
        $this->assign('id', Request::param('id'));
        return $this->fetch();
    }

    public function fetch_sub_anchors()
    {
        $admin_id = Request::param("admin_id");
        $order = Request::param("order");

        $searchid       = Request::param("id");
        $searchname     = Request::param("nick_name");
        $searchisanchor = Request::param("is_anchor");
        $searchisonline = Request::param("online_status");
        // 主播状态  1禁播
        $anchor_status = Request::param("anchor_status");
        // $searchvip = Request::param('vip_level');
        $searchaccount = Request::param("account");
        $mobile        = Request::param("mobile");
        $regist_type   = Request::param("regist_type");
        $start_time    = Request::param("start_time");
        $end_time      = Request::param("end_time");

        $where = [
            ['is_anchor', '=', 1]
        ];

        if ($searchid) {
            $where[] = ['id', '=', $searchid];
        }
        if ($searchname) {
            $where[] = ['nick_name', '=', $searchname];
        }
        if ($searchisanchor != '') {
            $where[] = ['is_anchor', '=', $searchisanchor];
        }
        if ($searchaccount != '') {
            $where[] = ['account', '=', $searchaccount];
        }
        if ($mobile != '') {
            $where[] = ['mobile', '=', $mobile];
        }
        if ($regist_type != '') {
            $where[] = ['regist_type', '=', $regist_type];
        }
        if ($start_time != '') {
            $where[] = ["auth_time", ">", $start_time];
        }
        if ($end_time != '') {
            $where[] = ["auth_time", "<=", $end_time];
        }

        // 禁播用户查询
        if ($anchor_status == 1) {
            $banned_uid = AnchorBannedModel::where('ban_time', 0)->whereOr('ban_time', '>=', time())->column('anchor_id');
            if ($banned_uid) {
                $where[] = ['id', 'in', $banned_uid];
            } else {
                // 没有禁播的时候
                $where[] = ['id', '=', 0];
            }
        }

        if ($order == '') {
            $order = ['regist_time' => 'desc'];
        } else {
            $order = ['auth_time' => $order];
        }

        $page  = Request::param("page");
        $limit = Request::param("limit");

        // 正在直播中的
        if ($searchisonline != '') {
            $in_live_ids = LiveModel::column('anchorid');
            $in_live_ids = !empty($in_live_ids) ? $in_live_ids : [0];
            if ($searchisonline == 1) {
                $where[] = ['id', 'in', $in_live_ids];
            } else if ($searchisonline == 2) {
                $where[] = ['id', 'not in', $in_live_ids];
            }
        }

        $userlist = UserModel::where($where)->with(['inLive', 'anchorAuth', 'guild', 'anchorLiveNotice', 'anchorBanned' => function ($query) {
            $query->where('ban_time', 0)->whereOr('ban_time', '>=', time());
        }, 'recommend'                                                                                                  => function (Query $query) {
            $query->field('user_id,total_recommend,total_noble');
        }])->limit(($page - 1) * $limit, $limit)->order($order)->select();

        if (count($userlist) > 0) {
            $count = UserModel::where($where)->count("id");

            // 查询粉丝数
            $anchorid_arr = array_column($userlist->toArray(), 'id');
            $anchorid_arr = array_filter(array_unique($anchorid_arr));
            $fans_count   = AnchorFansModel::whereIn('anchorid', $anchorid_arr)->field('anchorid,count(id) as total')->group('anchorid')->select()->toArray();
            $fans_count   = array_column($fans_count, 'total', 'anchorid');


            $sub_anchors = AdminModel::get($admin_id);
            foreach ($userlist as &$value) {
                $_sub_anchors = explode(",", $sub_anchors->sub_anchors);
                if (in_array($value['id'], $_sub_anchors)) {
                    $value['sub_anchors'] = true;
                    $value['LAY_CHECKED'] = true;
                } else {
                    $value['sub_anchors'] = false;
                    $value['LAY_CHECKED'] = false;
                }

                $value['admin_id'] = $admin_id;

                $value['advertising'] = stripslashes($value['advertising']);
                $value["mobile"]      = mobileHide($value['mobile'], $this->userinfo->roleid);
                $value["account"]     = mobileHide($value['account'], $this->userinfo->roleid);
                $value['tag'] = ConfigTagModel::get($value['tags'])['title'] ?? '';

                // 粉丝数
                $value['fans_count'] = isset($fans_count[$value['id']]) ? $fans_count[$value['id']] : 0;

                if (empty($value["anchor_banned"])) {
                    continue;
                }

                $time = $value["anchor_banned"]["ban_time"] - time();
                if ($time > 0) {
                    $date = [
                        'day'    => intval($time / (24 * 3600)),
                        'hour'   => intval(($time % (24 * 3600)) / 3600),
                        'minute' => intval((($time % (24 * 3600)) % 3600) / 60),
                    ];

                    $value["anchor_banned"]["ban_time_format"] = "{$date['day']}天{$date['hour']}时{$date['minute']}分";
                } else if ($value["anchor_banned"]["ban_time"] == 0) {
                    $value["anchor_banned"]["ban_time_format"] = "永久";
                } else {
                    $value["anchor_banned"]["ban_time_format"] = "";
                }
            }

            return json(["code" => 0, "msg" => "", "data" => $userlist, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function update_sub_anchors()
    {
        $ids = Request::param("ids");
        $admin_id = Request::param("admin_id");
        $checked = Request::param("checked");
        $row = AdminModel::get($admin_id);
        $db_ids = [];
        $marge_ids = [];
        if ($row->sub_anchors != "") {
            $db_ids = explode(",", $row['sub_anchors']);
        }
        if ($checked == "true") {
            $marge_ids = array_merge($ids, $db_ids);
            $row->sub_anchors = implode(",", array_unique($marge_ids));

            if ($row->save()) {
                return self::bulidSuccess([], '更新成功');
            }
        } else {
            for ($i = 0; $i < count($ids); $i++) {
                $key = array_search($ids[$i], $db_ids);
                unset($db_ids[$key]);
            }
            $row->sub_anchors = implode(",", array_unique($db_ids));
            if ($row->save()) {
                return self::bulidSuccess([], '更新成功');
            }
        }


        return self::bulidFail("更新失败");
    }
}
